<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket聊天测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .input-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        input {
            width: 200px;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
            margin-left: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            font-weight: bold;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .messages {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin: 10px 0;
            background-color: #f8f9fa;
        }
        .message {
            margin-bottom: 10px;
            padding: 5px;
            border-radius: 4px;
        }
        .message.system {
            background-color: #e9ecef;
            color: #6c757d;
            font-style: italic;
        }
        .message.user {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        .message.own {
            background-color: #d4edda;
            color: #155724;
            text-align: right;
        }
        .info-panel {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-top: 20px;
        }
        .info-box {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            border: 1px solid #dee2e6;
        }
        .info-box h3 {
            margin-top: 0;
            color: #495057;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>WebSocket聊天测试</h1>
        
        <div class="input-group">
            <label for="userId">用户ID:</label>
            <input type="text" id="userId" placeholder="请输入用户ID" value="user1">
            <button id="connectBtn" onclick="connect()">连接</button>
            <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
        </div>
        
        <div id="status" class="status disconnected">未连接</div>
        
        <div class="input-group">
            <label for="messageInput">消息:</label>
            <input type="text" id="messageInput" placeholder="请输入消息" disabled>
            <button id="sendBtn" onclick="sendMessage()" disabled>发送</button>
        </div>
        
        <div id="messages" class="messages"></div>
        
        <div class="info-panel">
            <div class="info-box">
                <h3>连接信息</h3>
                <p><strong>端点:</strong> /ws/chat/{userId}</p>
                <p><strong>状态:</strong> <span id="connectionStatus">未连接</span></p>
                <p><strong>在线用户数:</strong> <span id="onlineCount">0</span></p>
            </div>
            
            <div class="info-box">
                <h3>在线用户</h3>
                <div id="onlineUsers">无</div>
            </div>
        </div>
    </div>

    <script>
        let websocket = null;
        let currentUserId = null;
        
        // 连接WebSocket
        function connect() {
            const userId = document.getElementById('userId').value.trim();
            if (!userId) {
                alert('请输入用户ID');
                return;
            }
            
            currentUserId = userId;
            const wsUrl = `ws://localhost:8080/ws/chat/${userId}`;
            
            try {
                websocket = new WebSocket(wsUrl);
                
                websocket.onopen = function(event) {
                    updateStatus('已连接', 'connected');
                    document.getElementById('connectBtn').disabled = true;
                    document.getElementById('disconnectBtn').disabled = false;
                    document.getElementById('messageInput').disabled = false;
                    document.getElementById('sendBtn').disabled = false;
                    document.getElementById('connectionStatus').textContent = '已连接';
                    
                    addMessage('系统', '连接成功', 'system');
                    updateOnlineInfo();
                };
                
                websocket.onmessage = function(event) {
                    addMessage('服务器', event.data, 'user');
                };
                
                websocket.onclose = function(event) {
                    updateStatus('连接已关闭', 'disconnected');
                    document.getElementById('connectBtn').disabled = false;
                    document.getElementById('disconnectBtn').disabled = true;
                    document.getElementById('messageInput').disabled = true;
                    document.getElementById('sendBtn').disabled = true;
                    document.getElementById('connectionStatus').textContent = '已断开';
                    
                    addMessage('系统', '连接已关闭', 'system');
                };
                
                websocket.onerror = function(error) {
                    console.error('WebSocket错误:', error);
                    addMessage('系统', '连接错误', 'system');
                };
                
            } catch (error) {
                console.error('连接失败:', error);
                alert('连接失败: ' + error.message);
            }
        }
        
        // 断开连接
        function disconnect() {
            if (websocket) {
                websocket.close();
                websocket = null;
            }
        }
        
        // 发送消息
        function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();
            
            if (!message) {
                alert('请输入消息');
                return;
            }
            
            if (websocket && websocket.readyState === WebSocket.OPEN) {
                websocket.send(message);
                addMessage('我', message, 'own');
                messageInput.value = '';
            } else {
                alert('WebSocket未连接');
            }
        }
        
        // 更新状态
        function updateStatus(message, className) {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = message;
            statusDiv.className = `status ${className}`;
        }
        
        // 添加消息到显示区域
        function addMessage(sender, message, type) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            messageDiv.innerHTML = `<strong>${sender}:</strong> ${message}`;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 更新在线信息
        function updateOnlineInfo() {
            fetch('/api/websocket/online-count')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        document.getElementById('onlineCount').textContent = data.data;
                    }
                })
                .catch(error => console.error('获取在线用户数失败:', error));
                
            fetch('/api/websocket/online-users')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        const users = data.data;
                        const usersDiv = document.getElementById('onlineUsers');
                        if (users && users.size > 0) {
                            usersDiv.textContent = Array.from(users).join(', ');
                        } else {
                            usersDiv.textContent = '无';
                        }
                    }
                })
                .catch(error => console.error('获取在线用户失败:', error));
        }
        
        // 回车发送消息
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
        
        // 定期更新在线信息
        setInterval(updateOnlineInfo, 5000);
        
        // 页面加载完成后自动连接（可选）
        // window.onload = function() {
        //     connect();
        // };
    </script>
</body>
</html>
